﻿using IOA.MES.Business;
using IOA.MES.ClientApi.Models.Request.Machine;
using IOA.MES.ClientApi.Models.Response.Machine;
using IOA.MES.Common;
using IOA.MES.DataAccess.Enum;
using IOA.MES.DataAccess.VModel;
using Newtonsoft.Json;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace IOA.MES.ClientApi.Controllers
{
    public class MachineController : ApiController
    {
        private Logger logger = LogManager.GetCurrentClassLogger();

        /// <summary>
        /// 查询设备列表
        /// </summary>
        [HttpPost]
        public ResultJson<QueryMachinesResponse> QueryMachines([FromBody] QueryMachinesRequest request)
        {
            var count = 0;
            var machines = new MachineMgr().QueryMachines(1, 0, out count, request.WorkshopCode, 0, DataAccess.Enum.CommonStatus.Normal);
            if (request.MachineType.HasValue)
            {
                machines = machines.Where(_ => _.MachineType == request.MachineType.Value).ToList();
            }

            var ivSqls = new List<VIVLocalData>();
            if (request.MachineType == MachineType.IV && machines.Any())
            {
                ivSqls.AddRange(new IVLocalDataMgr().Query(machines.Select(_ => _.PkId).Distinct().ToList()));
            }
            return new ResultJson<QueryMachinesResponse>(new QueryMachinesResponse
            {
                Machines = machines.Select(_ => new Machine
                {
                    MachineId = _.PkId,
                    MachineNo = _.MachineNo,
                    MachineName = _.MachineName,
                    WorkshopCode = _.WorkshopCode,
                    WorkshopName = _.WorkshopName,
                    CNMachineType = _.CNMachineType,
                    IvSql = ivSqls.FirstOrDefault(i => i.MachineId == _.PkId)?.Sql ?? string.Empty,
                    FileType = new List<string> { "众森" }.Contains(_.Manufacturers, StringComparer.CurrentCultureIgnoreCase) ? 0 : 1
                }).ToList()
            }, count);
        }

        /// <summary>
        /// 组件过站
        /// </summary>
        [HttpPost]
        public ResultJson<ViaSiteResponse> ViaSite([FromBody] ViaSiteRequest request)
        {
            if (string.IsNullOrWhiteSpace(request.Code))
            {
                throw new MultiLanBizException(110001, request.Code);// "组件条码不存在"
            }
            request.Code = request.Code.Replace("\r", "").Replace("\\r", "").ToUpper().Trim();

            var user = BaseEnv.User;
            var viaSiteRecord = new VProductViaSiteRecord
            {
                WorkshopCode = BaseEnv.WorkshopCode,
                SiteType = request.SiteType,
                Code = request.Code,
                CreateBy = user.PkId,
                MachineId = request.MachineId,
                DutyId = request.DutyId,
                BoxCode = request.BoxCode,
                IsLock = request.IsLock,
                QLevel = request.QLevel,
                TopPosition = request.TopPosition,
                BadCode = string.Join(",", request.BadReasons ?? new List<string>()),
                BadCoordinates = request.BadCoordinates,
                BadCount = request.BadCount,
                ComponentType = request.ComponentType,
                CellFeature = request.CellFeature,
                VerifyCode = request.VerifyCode
            };
            if (viaSiteRecord.SiteType == SiteType.Welding && viaSiteRecord.MachineId <= 0)
            {
                viaSiteRecord.MachineId = new MachineMgr().GetMachine(BaseEnv.WorkshopCode, MachineType.WeldingMachine, request.MachineIndex)?.PkId ?? 0;
                if (viaSiteRecord.MachineId <= 0)
                {
                    throw new MultiLanBizException(119003);// "设备不存在或已被删除"
                }
            }

            VProductViaSiteWeldData weldData = null;
            VProductViaSiteTopData topData = null;
            VProductViaSiteIVData ivData = null;
            List<VProductViaSiteImage> images = new List<VProductViaSiteImage>();
            if (viaSiteRecord.SiteType == SiteType.Welding)
            {
                weldData = new VProductViaSiteWeldData
                {
                    BarCode = request.Code,
                    FullData = JsonConvert.SerializeObject(request.WeldingData),
                    CreateBy = user.PkId
                };
                if (request.WeldingData != null && request.WeldingData.Any())
                {
                    foreach (var properity in weldData.GetType().GetProperties())
                    {
                        var keyValue = request.WeldingData.FirstOrDefault(_ => string.Equals(_.Key, properity.Name, StringComparison.CurrentCultureIgnoreCase));
                        if (keyValue.Value != null)
                        {
                            if (properity.PropertyType == typeof(decimal))
                            {
                                properity.SetValue(weldData, string.IsNullOrWhiteSpace(keyValue.Value) ? 0 : Convert.ToDecimal(keyValue.Value));
                            }
                            else
                            {
                                properity.SetValue(weldData, keyValue.Value);
                            }
                        }
                    }
                }
            }
            else if (viaSiteRecord.SiteType == SiteType.EL1 
                //|| viaSiteRecord.SiteType == SiteType.EL2
                )
            {
                images = request.ElResults.Select(_ => new VProductViaSiteImage
                {
                    SiteType = request.SiteType,
                    BarCode = request.Code,
                    Image = _.Image,
                    Positions = JsonConvert.SerializeObject(_.Positions)
                }).ToList();
            }
            else if (viaSiteRecord.SiteType == SiteType.Top)
            {
                topData = new VProductViaSiteTopData
                {
                    BarCode = request.Code,
                    CreateBy = user.PkId
                };
                if (request.TopData != null && request.TopData.Any())
                {
                    foreach (var properity in topData.GetType().GetProperties())
                    {
                        var keyValue = request.TopData.FirstOrDefault(_ => string.Equals(_.Key, properity.Name, StringComparison.CurrentCultureIgnoreCase));
                        if (keyValue.Value != null)
                        {
                            try
                            {
                                properity.SetValue(topData, keyValue.Value);
                            }
                            catch (Exception ex)
                            {
                                logger.Fatal(ex, $"Top转换出现异常，条码：{request.Code}，异常信息：{ex.Message}");
                            }
                        }
                    }
                }
            }
            else if (viaSiteRecord.SiteType == SiteType.Framing)
            {
                images = request.Images.Select(_ => new VProductViaSiteImage
                {
                    SiteType = request.SiteType,
                    BarCode = request.Code,
                    Image = _
                }).ToList();
            }
            else if (viaSiteRecord.SiteType == SiteType.IVTest)
            {
                images = request.Images.Select(_ => new VProductViaSiteImage
                {
                    SiteType = request.SiteType,
                    BarCode = request.Code,
                    Image = _
                }).ToList();
                ivData = new VProductViaSiteIVData
                {
                    BarCode = request.Code,
                    FullData = JsonConvert.SerializeObject(request.IVData),
                    CreateBy = user.PkId
                };
                if (request.IVData != null && request.IVData.Any())
                {
                    foreach (var properity in ivData.GetType().GetProperties())
                    {
                        var keyValue = request.IVData.FirstOrDefault(_ => string.Equals(_.Key, properity.Name, System.StringComparison.CurrentCultureIgnoreCase));
                        if (keyValue.Value != null)
                        {
                            try
                            {
                                if (properity.PropertyType == typeof(Decimal?))
                                {
                                    properity.SetValue(ivData, string.IsNullOrWhiteSpace(keyValue.Value) ? (decimal?)null : (decimal)Convert.ToDouble(keyValue.Value.Replace(",", ".").Replace("，", ".")));
                                }
                                else if (properity.PropertyType == typeof(Decimal))
                                {
                                    properity.SetValue(ivData, string.IsNullOrWhiteSpace(keyValue.Value) ? 0 : (decimal)Convert.ToDouble(keyValue.Value.Replace(",", ".").Replace("，", ".")));
                                }
                                else
                                {
                                    properity.SetValue(ivData, keyValue.Value.Replace(",", ".").Replace("，", "."));
                                }
                            }
                            catch (Exception ex)
                            {
                                logger.Fatal(ex, $"IV转换出现异常，条码：{request.Code}，异常信息：{ex.Message}，IvData：{JsonConvert.SerializeObject(request.IVData)}");
                            }
                        }
                    }
                }
            }

            VProductViaSiteRecord model = null;
            int dutyId = 0;
            try
            {
                model = new ProductViaSiteMgr().ViaSite(viaSiteRecord, out dutyId, images, weldData, topData, ivData, request.InsulateData);
            }
            catch (MultiLanBizException ex)
            {
                //标片测试
                if (ex.ErrCode >= 110018 && ex.ErrCode <= 110021)
                {
                    if (ex.ErrCode == 110021)
                    {
                        var machine = new MachineMgr().GetMachine(request.MachineId);
                        logger.Debug($"设备 【{request.MachineId}】 IV标片测定合格！当前结果：{machine?.IvStandardPieceTestResult}");
                        return new ResultJson<ViaSiteResponse>(new ViaSiteResponse
                        {
                            StandardTestResult = new StandardTestResult
                            {
                                Pass = true
                            }
                        });
                    }
                    else
                    {
                        logger.Debug($"设备 【{request.MachineId}】 IV标片测定不合格：{ex.Message}");
                        return new ResultJson<ViaSiteResponse>(new ViaSiteResponse
                        {
                            StandardTestResult = new StandardTestResult
                            {
                                Pass = false,
                                ErrMsg = BaseEnv.GetErrMsg(ex.ErrCode, ex.Message)
                            }
                        });
                    }
                }
                throw;
            }
            var total = 0;
            var models = new ProductSiteBomMgr().Query(1, 0, out total, "", model.WorkOrderNo, model.SiteType);
            var storages = models == null || !models.Any() ? new List<VStorage>() : new WarehouseMgr().QueryProductWorkshopWarehouseStorages(request.Code);
            var output = request.SiteType != SiteType.Laminated ? 0
                : new ProductViaSiteMgr().GetCurDutyViaSiteOutput(dutyId, model.SiteType, model.MachineId);

            var response = new ResultJson<ViaSiteResponse>(new ViaSiteResponse
            {
                DutyId = dutyId,
                Output = output,
                ViaSiteRecord = new ViaSiteRecord
                {
                    Code = model.Code,
                    WorkOrderNo = model.WorkOrderNo,
                    OrderNo = model.OrderNo,
                    QLevel = model.QLevel,
                    BadReason = model.BadReason,
                    DutyName = model.DutyName,
                    TopPosition = model.TopPosition,
                    MachineName = model.MachineName,
                    OperateTime = model.CreateTime,
                    Operator = user.TrueName
                },
                Boms = new List<WorkOrderBom>(),
                //Boms = models.Select(_ => new WorkOrderBom
                //{
                //    //BatchNo = _.BatchNo,
                //    //BomCount = _.BomCount,
                //    //ProductCode = _.BomProductCode,
                //    //ProductName = _.BomProductName,
                //    //RemainCount = storages.FirstOrDefault(s => string.Equals(s.ProductCode, _.BomProductCode, System.StringComparison.CurrentCultureIgnoreCase))?.Quantity ?? 0
                //}).ToList(),
                IVData = model.SiteType != SiteType.IVTest ? null : new IVData
                {
                    PowerLevel = ivData.IVPowerLevel,
                    CurrentLevel = ivData.IVCurrentLevel,
                    BarCode = model.Code,
                    Pmax = ivData.Pmax
                }
            });

            if (model.SiteType == SiteType.NQC)
            {
                var topRecords = request.SiteType != SiteType.NQC ? new List<VProductViaSiteRecord>() : new ProductViaSiteMgr().GetProductViaSiteRecord(request.Code, SiteType.Top);
                response.Data.ViaSiteRecord.TopMachine = topRecords.FirstOrDefault()?.MachineName ?? string.Empty;
                response.Data.ViaSiteRecord.TopPosition = topRecords.FirstOrDefault()?.TopPosition ?? string.Empty;
            }
            else if (model.SiteType == SiteType.Sort)
            {
                response.Data.SortStacks = QuerySortStacks(new QuerySortStacksRequest
                {
                    MachineId = model.MachineId,
                    BarCode = model.Code
                }).Data.Stacks;
            }
            return response;
        }

        /// <summary>
        /// 提交层压机配置
        /// </summary>
        [HttpPost]
        public ResultJson<object> SubmitTopMachineSetting([FromBody] SubmitTopMachineSettingRequest requet)
        {
            new MachineMgr().SaveTopMachineSetting(new VTopMachineSetting
            {
                MachineId = requet.MachineId,
                Layer = requet.Layer,
                Cavity = requet.Cavity,
                InflationTime = requet.InflationTime,
                Pressure1 = requet.Pressure1,
                Pressure2 = requet.Pressure2,
                Pressure3 = requet.Pressure3,
                PressureDelayTime1 = requet.PressureDelayTime1,
                PressureDelayTime2 = requet.PressureDelayTime2,
                Temp = requet.Temp,
                TopTime = requet.TopTime,
                UpperVacuumDelayTime = requet.UpperVacuumDelayTime,
                VacuumPumpingTime = requet.VacuumPumpingTime
            });
            return new ResultJson<object>();
        }

        /// <summary>
        /// 查询组件过站记录
        /// </summary>
        [HttpPost]
        public ResultJson<QueryViaSiteRecordsResponse> QueryViaSiteRecords([FromBody] QueryViaSiteRecordsRequest request)
        {
            var total = 0;
            var models = new ProductViaSiteMgr().QueryViaSiteRecords(1, 0, out total, request.DutyId, request.SiteType, request.MachineId);
            total = new ProductViaSiteMgr().GetCurDutyViaSiteOutput(request.DutyId, request.SiteType, request.MachineId);
            var users = !models.Any() ? new List<VUser>() : new UserMgr().QueryUsers(models.Select(_ => _.CreateBy).Distinct().ToList());
            var topRecords = request.SiteType != SiteType.NQC ? new List<VProductViaSiteRecord>()
                : new ProductViaSiteMgr().QueryProductViaSiteRecords(models.Select(_ => _.Code.ToUpper()).Distinct().ToList(), SiteType.Top);
            return new ResultJson<QueryViaSiteRecordsResponse>(new QueryViaSiteRecordsResponse
            {
                Records = models.Select(model => new ViaSiteRecord
                {
                    Code = model.Code,
                    WorkOrderNo = model.WorkOrderNo,
                    QLevel = model.QLevel,
                    BadReason = model.BadReason,
                    OrderNo = model.OrderNo,
                    DutyName = model.DutyName,
                    MachineName = model.MachineName,
                    OperateTime = model.CreateTime,
                    TopPosition = request.SiteType == SiteType.Top ? model.TopPosition : (request.SiteType != SiteType.NQC ? string.Empty : topRecords.LastOrDefault(_ => string.Equals(model.Code, _.Code, StringComparison.CurrentCultureIgnoreCase))?.TopPosition),
                    TopMachine = request.SiteType == SiteType.Top ? model.MachineName : (request.SiteType != SiteType.NQC ? string.Empty : topRecords.FirstOrDefault(_ => string.Equals(model.Code, _.Code, StringComparison.CurrentCultureIgnoreCase))?.MachineName),
                    Operator = users.FirstOrDefault(_ => _.PkId == model.CreateBy)?.TrueName
                }).ToList()
            }, total);
        }

        /// <summary>
        /// 查询漏扫记录
        /// </summary>
        [HttpPost]
        public ResultJson<QueryMissingViaSiteRecordsResponse> QueryMissingViaSiteRecords([FromBody] QueryMissingViaSiteRecordsRequest request)
        {
            var total = 0;
            var records = new ProductViaSiteMgr().QueryMissingRecords(request.PageIndex, request.PageSize, out total, BaseEnv.WorkshopCode, request.SiteType, request.MachineId, request.StartTime, request.EndTime);
            return new ResultJson<QueryMissingViaSiteRecordsResponse>(new QueryMissingViaSiteRecordsResponse
            {
                Components = records.Select(_ => new Component
                {
                    BarCode = _.BarCode,
                    OrderNo = _.OrderNo,
                    WorkOrderNo = _.WorkOrderNo,
                    WorkshopCode = _.WorkshopCode,
                    WorkshopName = _.WorkshopName,
                    DistributeTime = _.DistributeTime.Value
                }).ToList()
            }, total);
        }

        /// <summary>
        /// 获取组件详情
        /// </summary>
        [HttpPost]
        public ResultJson<GetComponentResponse> GetComponent([FromBody] GetComponentRequest request)
        {
            request.BarCode = request.BarCode.Replace("\r", "").Replace("\\r", "").ToUpper().Trim();
            var component = new ComponentMgr().GetComponent(request.BarCode);
            if (component == null)
            {
                var stand = new StandardPieceMgr().GetStandardPiece(request.BarCode);
                if (stand != null)
                {
                    component = new VComponent
                    {
                        BarCode = stand.ProductCode,
                        WorkOrderNo = "StandPiece"
                    };
                }
            }
            var viaSiteRecords = new ProductViaSiteMgr().GetProductViaSiteRecord(request.BarCode, SiteType.Welding);
            return new ResultJson<GetComponentResponse>(new GetComponentResponse
            {
                Component = component == null ? null : new Component
                {
                    BarCode = component.BarCode,
                    OrderNo = component.OrderNo,
                    WorkOrderNo = component.WorkOrderNo,
                    WorkshopCode = component.WorkshopCode,
                    WorkshopName = component.WorkshopName,
                    CellColor = component.CellColor,
                    CellEfficiency = component.CellEfficiency,
                    WeldingMachineName = viaSiteRecords.FirstOrDefault()?.MachineName,
                    IVPowerLevel = component.IVPowerLevel ?? 0,
                    DistributeTime = component.DistributeTime ?? DateTime.MinValue,
                    TheoreticalPower = component.TheoreticalPower
                }
            });
        }

        /// <summary>
        /// 查询条码标签
        /// </summary>
        [HttpPost]
        public ResultJson<GetWorkOrderLabelsResponse> GetWorkOrderLabels([FromBody] GetWorkOrderLabelsRequest request)
        {
            var component = new ComponentMgr().GetComponent(request.BarCode);
            if (component == null)
            {
                throw new MultiLanBizException(110001, request.BarCode);// "组件条码不存在");
            }
            var workOrderLabel = string.IsNullOrWhiteSpace(request.WorkOrderNo) ? new LabelMgr().GetLabelByCode(request.BarCode)
                : new LabelMgr().GetWorkOrderLabel("", request.WorkOrderNo);
            var response = new GetWorkOrderLabelsResponse
            {
                BarCode = request.BarCode,
                Labels = GetLabels(workOrderLabel, component)
            };

            return new ResultJson<GetWorkOrderLabelsResponse>(response);
        }

        /// <summary>
        /// 查询工单标签
        /// </summary>
        [HttpPost]
        public ResultJson<GetWorkOrderLabelsPreviewResponse> GetWorkOrderLabelsPreview([FromBody] GetWorkOrderLabelsPreviewRequest request)
        {
            var workOrderLabel = new LabelMgr().GetWorkOrderLabel("", request.WorkOrderNo);
            var response = new GetWorkOrderLabelsPreviewResponse
            {
                Labels = GetLabels(workOrderLabel)
            };

            return new ResultJson<GetWorkOrderLabelsPreviewResponse>(response);
        }

        private List<Label> GetLabels(VWorkorderLable workOrderLabel, VComponent component = null)
        {
            var labels = new List<Label>();
            if (workOrderLabel != null)
            {
                if (!string.IsNullOrWhiteSpace(workOrderLabel.SerialNum))
                {
                    labels.Add(new Label { LabelName = "序列号", TableName = "序列号", LabelFile = workOrderLabel.SerialNum });
                }
                if (!string.IsNullOrWhiteSpace(workOrderLabel.BorderBarCode))
                {
                    var label = new Label { LabelName = "边框条码", TableName = "条码", LabelFile = workOrderLabel.BorderBarCode };
                    if (component != null)
                    {
                        var ivData = new ProductViaSiteMgr().GetIvData(component.BarCode);
                        if (ivData == null)
                        {
                            throw new MultiLanBizException(110099, component.BarCode);// "IV数据不存在，请重新过IV"
                        }
                        var power = new BinningSchemeMgr().GetBinningPower(ivData.PowerId);
                        if (power == null)
                        {
                            throw new MultiLanBizException(135007);//该功率档不存在
                        }
                        label.LabelData = new List<KeyValuePair<string, string>>
                        {
                            new KeyValuePair<string, string>("条码",component.BarCode),
                            new KeyValuePair<string, string>("额定功率", component.IVPowerLevel.HasValue ? component.IVPowerLevel.Value.ToString("0") : ""),
                            new KeyValuePair<string, string>("档位", component.IVCurrentLevel),
                            new KeyValuePair<string, string>("spmax",$"{power.Pmax??string.Empty} W"),
                            new KeyValuePair<string, string>("simp", $"{power.Impp??string.Empty}"),
                            new KeyValuePair<string, string>("svmp", $"{power.Vmpp??string.Empty}"),
                            new KeyValuePair<string, string>("sisc", $"{power.Isc??string.Empty}"),
                            new KeyValuePair<string, string>("svoc", $"{power.Voc??string.Empty}"),
                            new KeyValuePair<string, string>("时间", ivData.CreateTime.ToString("yyyy年MM月dd日HH时mm分ss秒")),
                            new KeyValuePair<string, string>("ArtNo", ""),
                            new KeyValuePair<string, string>("铭牌型号", power.NameplateModel)
                        };
                    }
                    labels.Add(label);
                }
                if (!string.IsNullOrWhiteSpace(workOrderLabel.Nameplate))
                {
                    var label = new Label { LabelName = "铭牌", TableName = "铭牌", LabelFile = workOrderLabel.Nameplate };
                    if (component != null)
                    {
                        var ivData = new ProductViaSiteMgr().GetIvData(component.BarCode);
                        if (ivData == null)
                        {
                            throw new MultiLanBizException(110099, component.BarCode);// "IV数据不存在，请重新过IV");
                        }
                        var power = new BinningSchemeMgr().GetBinningPower(ivData.PowerId);
                        if (power == null)
                        {
                            throw new MultiLanBizException(135007);//该功率档不存在
                        }
                        label.LabelData = new List<KeyValuePair<string, string>>
                        {
                            new KeyValuePair<string, string>("条码",component.BarCode),
                            new KeyValuePair<string, string>("额定功率", !component.IVPowerLevel.HasValue ? string.Empty : component.IVPowerLevel.Value.ToString("0") + " W"),
                            new KeyValuePair<string, string>("铭牌型号", ivData?.NameplateModel),
                            new KeyValuePair<string, string>("等级", component.QLevel),
                            new KeyValuePair<string, string>("档位", component.IVCurrentLevel),
                            new KeyValuePair<string, string>("颜色", component.ComponentColor),
                            new KeyValuePair<string, string>("bpmax", $"{power.Pmax??string.Empty} W"),
                            new KeyValuePair<string, string>("bimp", $"{power.Impp??string.Empty} A"),
                            new KeyValuePair<string, string>("bvmp", $"{power.Vmpp??string.Empty} V"),
                            new KeyValuePair<string, string>("bisc", $"{power.Isc??string.Empty} A"),
                            new KeyValuePair<string, string>("bvoc", $"{power.Voc??string.Empty} V"),
                            new KeyValuePair<string, string>("spmax", !ivData.Pmax.HasValue?string.Empty:ivData.Pmax.Value.ToString("0 W")),
                            new KeyValuePair<string, string>("simp", !ivData.Im.HasValue?string.Empty:ivData.Im.Value.ToString("0.00000000")),
                            new KeyValuePair<string, string>("svmp", !ivData.Vm.HasValue?string.Empty:ivData.Vm.Value.ToString("0.00000000")),
                            new KeyValuePair<string, string>("sisc", !ivData.Isc.HasValue?string.Empty:ivData.Isc.Value.ToString("0.00000000")),
                            new KeyValuePair<string, string>("svoc", !ivData.Voc.HasValue?string.Empty:ivData.Voc.Value.ToString("0.00000000")),
                            new KeyValuePair<string, string>("sff", !ivData.FF.HasValue?string.Empty:ivData.FF.Value.ToString("0.0000")),
                            new KeyValuePair<string, string>("stemp", !ivData.Temp.HasValue?string.Empty:ivData.Temp.Value.ToString("0.00")),
                            new KeyValuePair<string, string>("时间", ivData.CreateTime.ToString("yyyy年MM月dd日HH时mm分ss秒")),
                            new KeyValuePair<string, string>("mvolt", ""),
                            new KeyValuePair<string, string>("mfuse", ""),
                            new KeyValuePair<string, string>("iecvolt", ""),
                            new KeyValuePair<string, string>("iecfuse", ""),
                            new KeyValuePair<string, string>("Pre_fix", ""),
                            new KeyValuePair<string, string>("CountryOrigin", ""),
                            new KeyValuePair<string, string>("ArtNo", ""),
                            new KeyValuePair<string, string>("in_code", ""),
                            new KeyValuePair<string, string>("电池来源", ""),
                            new KeyValuePair<string, string>("背板", ""),
                            new KeyValuePair<string, string>("认证码", ""),
                            new KeyValuePair<string, string>("模型代码", ""),
                            new KeyValuePair<string, string>("认证日期", ""),
                            new KeyValuePair<string, string>("备注", ""),
                            new KeyValuePair<string, string>("协鑫二维码", ""),
                            new KeyValuePair<string, string>("隆基二维码", "")
                        };
                    }
                    labels.Add(label);
                }
                if (!string.IsNullOrWhiteSpace(workOrderLabel.CurrentTag))
                {
                    labels.Add(new Label { LabelName = "电流标签", TableName = "电流标", LabelFile = workOrderLabel.CurrentTag });
                }
                if (!string.IsNullOrWhiteSpace(workOrderLabel.EnergyTag))
                {
                    labels.Add(new Label { LabelName = "能源标签", TableName = "能源标签", LabelFile = workOrderLabel.EnergyTag });
                }
            }
            return labels;
        }

        /// <summary>
        /// 获取分拣机状态
        /// </summary>
        [HttpPost]
        public ResultJson<QuerySortStacksResponse> QuerySortStacks([FromBody] QuerySortStacksRequest request)
        {
            var response = new ResultJson<QuerySortStacksResponse>(new QuerySortStacksResponse());
            var rules = new SortMgr().QueryDisplayValidRules(BaseEnv.WorkshopCode, request.MachineId);
            var record = string.IsNullOrWhiteSpace(request.BarCode) ? null : new SortMgr().GetSortRecord(request.BarCode);

            var stacks = rules.Select(_ => new SortStack
            {
                StackNo = _.StackNo,
                SortNo = _.SortNo,
                Rules = _.Rules.Select(r => new KeyValuePair<string, string>(r.Key, r.Value)).ToList()
            }).ToList();
            if (record != null && stacks.Any(_ => _.StackNo == record.StackNo))
            {
                stacks.FirstOrDefault(_ => _.StackNo == record.StackNo).LastSort = true;
            }
            response.Data.Stacks = stacks;

            return response;
        }

        /// <summary>
        /// 分拣回流
        /// </summary>
        [HttpPost]
        public ResultJson<SortFlowbackResponse> SortFlowback([FromBody] SortFlowbackRequest request)
        {
            new SortMgr().Flowback(new VSortRecord
            {
                MachineId = request.MachineId,
                BarCode = request.BarCode,
                ModifyBy = BaseEnv.User.PkId
            });
            var response = new ResultJson<SortFlowbackResponse>(new SortFlowbackResponse());
            var rules = new SortMgr().QueryDisplayValidRules(BaseEnv.WorkshopCode, request.MachineId);
            var record = string.IsNullOrWhiteSpace(request.BarCode) ? null : new SortMgr().GetSortRecord(request.BarCode);
            var stacks = rules.Select(_ => new SortStack
            {
                StackNo = _.StackNo,
                SortNo = _.SortNo,
                Rules = _.Rules.Select(r => new KeyValuePair<string, string>(r.Key, r.Value)).ToList()
            }).ToList();
            if (record != null && stacks.Any(_ => _.StackNo == record.StackNo))
            {
                stacks.FirstOrDefault(_ => _.StackNo == record.StackNo).LastSort = true;
            }
            response.Data.Stacks = stacks;
            return response;
        }

        /// <summary>
        /// 清空堆
        /// </summary>
        [HttpPost]
        public ResultJson<ClearSortStackResponse> ClearSortStack([FromBody] ClearSortStackRequest request)
        {
            new SortMgr().ClearStack(new VSortStack
            {
                MachineId = request.MachineId,
                StackNo = request.StackNo,
                ModifyBy = BaseEnv.User.PkId
            });
            var response = new ResultJson<ClearSortStackResponse>(new ClearSortStackResponse());
            var rules = new SortMgr().QueryDisplayValidRules(BaseEnv.WorkshopCode, request.MachineId);
            response.Data.Stacks = rules.Select(_ => new SortStack
            {
                StackNo = _.StackNo,
                SortNo = _.SortNo,
                Rules = _.Rules.Select(r => new KeyValuePair<string, string>(r.Key, r.Value)).ToList()
            }).ToList();
            return response;
        }

        /// <summary>
        /// 分拣组件
        /// </summary>
        [HttpPost]
        public ResultJson<SortResponse> Sort([FromBody] SortRequest request)
        {
            var sortRecord = new SortMgr().SortComponent(new VSortRecord
            {
                BarCode = request.BarCode,
                MachineId = request.MachineId
            });

            return new ResultJson<SortResponse>(new SortResponse
            {
                WorkOrderNo = sortRecord.WorkOrderNo,
                StackNo = sortRecord.StackNo,
                FootProtect = sortRecord.FootProtect,
                SortStacks = QuerySortStacks(new QuerySortStacksRequest
                {
                    MachineId = request.MachineId,
                    BarCode = request.BarCode
                }).Data.Stacks
            });
        }
    }
}
